import { loginPCApi, sendCodePC } from '@/views/user/api/userApi'
import { useStore } from "@/store";
import { getCurrentInstance, reactive, ref } from "vue";
import { LoginParam } from '@/views/user/interface/interface';
import { Md5 } from 'ts-md5/dist/md5';
import { setUserInfo } from '@/global/session'
import { setCheckPassword, getCheckPassword } from '@/global/local'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { log } from 'console';

export default function userLogin() {
  const router = useRouter()
  const { proxy } = getCurrentInstance() as any;
  const store = useStore();
  //表单绑定的数据
  const loginModel = reactive<LoginParam>({
    userlogin: '',
    password: '',
    vertCode: '',
  })
  //表单验证规则
  const rules = reactive({
    userlogin: [{
      required: true,
      trigger: 'blur',
      message: '请填写登录账户'
    }],
    password: [{
      required: true,
      trigger: 'blur',
      message: '请填写登录密码'
    }],
    vertCode: [{
      required: true,
      trigger: 'blur',
      message: '请填写验证码'
    }],
  })
  //所有的导航
  const menuListAll = [
    {
      path: '/account/accountList',
      meta: {
        title: "账号管理",
        icon: "UserFilled",
      },
    },
    {
      path: "/family",
      meta: {
        title: "常驻人员数据查询",
        icon: "Platform",
        parentId: 0,
      },
      children: [
        {
          path: "/family/familyList",
          meta: {
            title: "常驻家庭管理",
            // icon: "DocumentChecked",
            parentId: 17,
          },
        },
        {
          path: "/family/epidemicList",
          meta: {
            title: "常驻人员防疫管理",
            // icon: "DocumentChecked",
            parentId: 17,
          },
        },
        {
          path: "/family/safeList",
          meta: {
            title: "常驻人员安全管理",
            // icon: "DocumentChecked",
            parentId: 17,
          },
        }
      ],
    },
    {
      path: '/extra/extraList',
      meta: {
        title: "来返人员数据统计",
        icon: "Promotion",
      },
    },
    {
      path: '/statistics/statisticsList',
      meta: {
        title: "数据统计",
        icon: "Histogram",
        
      },
    },
    {
      path: '/operation/operationList',
      meta: {
        title: "操作日志",
        icon: "List",
      },
    },
    {
      path: "/danger",
      meta: {
        title: "隐患管理",
        icon: "Checked",
      },
      children: [
        {
          path: "/danger/dangerConduct",
          meta: {
            title: "工单办理"
          },
        },
        {
          path: "/danger/approvalList",
          meta: {
            title: "审批列表"
          },
        },
        {
          path: "/danger/dangerList",
          meta: {
            title: "综合查询"
          },
        },
        {
          path: "/danger/analysisList",
          meta: {
            title: "统计分析"
          },
        }
      ],
    },
  ];
   const menuListAllCopy = [
    {
      path: '/account/accountList',
      meta: {
        title: "账号管理",
        icon: "UserFilled",
      },
    },
    {
      path: "/family",
      meta: {
        title: "常驻人员数据查询",
        icon: "Platform",
        parentId: 0,
      },
      children: [
        {
          path: "/family/familyList",
          meta: {
            title: "常驻家庭管理",
            // icon: "DocumentChecked",
            parentId: 17,
          },
        },
        {
          path: "/family/epidemicList",
          meta: {
            title: "常驻人员防疫管理",
            // icon: "DocumentChecked",
            parentId: 17,
          },
        },
        {
          path: "/family/safeList",
          meta: {
            title: "常驻人员安全管理",
            // icon: "DocumentChecked",
            parentId: 17,
          },
        }
      ],
    },
    {
      path: '/extra/extraList',
      meta: {
        title: "来返人员数据统计",
        icon: "Promotion",
      },
    },
    {
      path: '/statistics/statisticsList',
      meta: {
        title: "数据统计",
        icon: "Histogram",
        
      },
    },
    {
      path: '/operation/operationList',
      meta: {
        title: "操作日志",
        icon: "List",
      },
    },
    {
      path: "/danger",
      meta: {
        title: "隐患管理",
        icon: "Checked",
      },
      children: [
        {
          path: "/danger/dangerList",
          meta: {
            title: "隐患查询"
          },
        },
        {
          path: "/danger/analysisList",
          meta: {
            title: "统计分析"
          },
        }
      ],
    },
  ];
  const loading = ref<boolean>(false)
  //登录提交
  const onLogin = async () => {
    //表单验证
    proxy.$refs.loginFormRef.validate(async (valid: boolean) => {
      if (valid) {
        loading.value = true
        const params = {
          userlogin: loginModel.userlogin,
          password: Md5.hashStr(loginModel.password),
          vertCode: loginModel.vertCode
        }
        try {
          let res = await loginPCApi(params)
          if (res?.code === 0) {
            let menuList: any = []

            if (res.data.roleId == 1 || res.data.roleId == 2 || res.data.roleId == 3 || res.data.roleId == 4 || res.data.roleId == 5|| res.data.roleId == 6) {
              // 1、超级管理员  2、市级管理员 3、市级督察员  4、镇级管理员  5、村级管理员 6、市级直属部门
              setUserInfo(JSON.stringify(res.data))
              //localStorage 存储记住密码状态 1记住 2不记住
              let loginInfo = {
                checked: checked.value,
                login: {
                  userlogin: loginModel.userlogin,
                  password: loginModel.password
                }
              }
              console.log('+++++++++++++++++++++++++');
              setCheckPassword(JSON.stringify(loginInfo))
              let funcAuth = res.data.roleId == 5 ? ['2', '3', '4'] : res.data.funcAuth.split(',')
              if (res.data.roleId == 1) {
                console.log('1111')
                if (router.currentRoute.value.query.redirect) {
                  router.replace({ path: router.currentRoute.value.query.redirect as string })
                } else {
                  router.replace({ name: 'workbench' })
                }
                let workbench: any = [
                  {
                    path: '/workbench/workbench',
                    meta: {
                      title: "工作台",
                      icon: "Management",
                    }
                  }
                ]
                let menuListArr = workbench.concat(menuListAllCopy)
                console.log('222',menuListArr)
                menuList = menuListArr
                store.commit("menu/setMenuList", menuList)
              } else {
                console.log('2222')

                if (router.currentRoute.value.query.redirect) {
                  let redirect = router.currentRoute.value.query.redirect as string
                  let redirectArr = redirect.split('/')
                  let flag = (redirectArr[1] == 'account' && funcAuth.indexOf('1') !== -1)
                    || (redirectArr[1] == 'family' && funcAuth.indexOf('2') !== -1)
                    || (redirectArr[1] == 'extra' && funcAuth.indexOf('3') !== -1)
                    || (redirectArr[1] == 'statistics' && funcAuth.indexOf('4') !== -1)
                  if (flag) {
                    router.replace({ path: router.currentRoute.value.query.redirect as string })
                  } else {
                    menuList = onMenuList(funcAuth)
                    store.commit("menu/setMenuList", menuList)
                    router.replace({ name: 'workbench' })
                  }
                } else {
                  menuList = onMenuList(funcAuth)
                  store.commit("menu/setMenuList", menuList)
                  router.replace({ name: 'workbench' })
                }
              }
            } else {
              loading.value = false
              ElMessage({ type: 'info', message: '您没有权限进入系统，请联系管理员！' })
            }
          } else {
            loading.value = false
          }
        } catch {
          loading.value = false
        }
      }
    })
  }
  //设置导航列表
  const onMenuList = (funcAuth) => {
    let arr: any = [
      {
        path: '/workbench/workbench',
        meta: {
          title: "工作台",
          icon: "Management",
        }
      }
    ]
    if (funcAuth.indexOf('1') !== -1) {
      arr.push(menuListAll[0])
    }
    if (funcAuth.indexOf('2') !== -1) {
      arr.push(menuListAll[1])
    }
    if (funcAuth.indexOf('3') !== -1) {
      arr.push(menuListAll[2])
    }
    if (funcAuth.indexOf('4') !== -1) {
      arr.push(menuListAll[3])
    }
    if (funcAuth.indexOf('5') !== -1) {
      arr.push(menuListAll[5])
    }
    if (funcAuth.indexOf('6') !== -1) {
      arr.push(menuListAll[5])
    }
    return arr
  }

  //验证码
  const codeNum = ref(60);
  const getCodeFlag = ref(true);
  // const actForm = ref({
  //   userAccount: '',
  //   smsCode: '',
  // });
  // const loginModel = reactive<LoginParam>({
  //   userlogin: '',
  //   password: '',
  //   vertCode: '',
  // })

  const timer = ref<any>(null);
  const getCode = async () => {
    if(!getCodeFlag.value) return
    const reg = /^[1][3-9][0-9]{9}$/;
    if (reg.test(loginModel.userlogin)) {
      let res = await sendCodePC({ phone: loginModel.userlogin });
      if (res.code == 0) {
        ElMessage.success('已发送');
        getCodeFlag.value = false;
        timer.value = setInterval(() => {
          if (codeNum.value > 0) {
            codeNum.value--;
          } else {
            getCodeFlag.value = true;
            codeNum.value = 60;
            clearInterval(timer.value);
          }
        }, 1000);
      }
    } else { 
      ElMessage.warning('请输入正确的手机号');
    }
  };





  // 记住密码
  let checked = ref<boolean>(true)
  if (getCheckPassword()) {
    let obj = JSON.parse(getCheckPassword() as string)
    checked.value = obj.checked
    if (checked.value) {
      loginModel.userlogin = obj.login.userlogin
      loginModel.password = obj.login.password
    }
  } else {
    checked.value = false
  }
  return {
    loginModel,
    rules,
    loading,
    onLogin,
    checked,
    getCodeFlag,
    getCode,
    codeNum
  }
}